<template>
  <div class="app-container dept">
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item prop="name">
         <span slot="label">
          部门名称
          <el-tooltip content="树形表格不支持模糊查询" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </span>
        <el-input
          v-model="queryParams.name"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!--        <el-button icon="el-icon-question" size="mini" @click="()=>utils.openHelp(this,'')">帮助</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          :disabled="single"
          v-hasPermi="['system:dept:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button

          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dept:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button

          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dept:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="deptList"
      row-key="branchinnercode"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleUpdate"
      stripe border
      
      @row-contextmenu="(row,column,e)=>utils.rightBtn(row,column,e,this,'table')"
    >
      <el-table-column type="selection" width="60" align="center"/>
      <el-table-column prop="name" label="机构名称" width="260"></el-table-column>
      <el-table-column prop="branchcode" label="机构编码" width="100"></el-table-column>
      <el-table-column prop="managerName" label="机构主管" width="100"></el-table-column>
      <el-table-column label="是否管理部门" width="100" align="center">
        <template slot-scope="scope">
          <span class="label label-danger" v-if="scope.row.ismanagement=='N'">否</span>
          <span v-else-if="scope.row.ismanagement=='Y'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否生产部门" width="100" align="center">
        <template slot-scope="scope">
          <span class="label label-danger" v-if="scope.row.ischeckup=='N'">否</span>
          <span v-else-if="scope.row.ischeckup=='Y'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否停用" align="center">
        <template slot-scope="scope">
          <span class="label label-danger" v-if="scope.row.isstop=='Y'">停用</span>
          <span v-else-if="scope.row.isstop=='N'">正常</span>
        </template>
      </el-table-column>
      <el-table-column label="维修单位" align="center">
        <template slot-scope="scope">
          <span class="label label-danger" v-if="scope.row.prop2=='N'">否</span>
          <span v-else-if="scope.row.prop2=='Y'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否统计" align="center">
        <template slot-scope="scope">
          <span class="label label-danger" v-if="scope.row.prop3=='N'">否</span>
          <span v-else-if="scope.row.prop3=='Y'">是</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" align="center" width="150"></el-table-column>
      <el-table-column prop="fax" label="传真" width="100"></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.username !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" :modal="false" :appendToBody="false" width="70%" :top="scrollTop"
               v-dialog-drag :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" v-if="isparentinnercode">
            <el-form-item label="上级机构" prop="parentName">
              <el-input v-model="form.parentName" placeholder="请选择上级机构" @click.native="openOrganization()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称" prop="name">
              <el-input v-model="form.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="form.fax"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定员" prop="ratednum">
              <el-input v-model="form.ratednum"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在编人数" prop="onstaffnum">
              <el-input v-model="form.onstaffnum"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编外人数" prop="offstaffnum">
              <el-input v-model="form.offstaffnum"/>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="机构主管" prop="managerName">
              <el-input v-model="form.managerName"
                        readonly
                        @click.native="utils.openDialog('2',['realname','username'],['managerName','manager'], that)"
                        placeholder="请选择机构主管">
                <el-button slot="append" icon="el-icon-search" @click.native="utils.openDialog('2',['realname','username'],['managerName','manager'], that)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="上级主管领导" prop="leader1Name">
              <el-input v-model="form.leader1Name"
                        readonly
                        @click.native="utils.openDialog('2',['realname','username'],['leader1Name','leader1'], that)"
                        placeholder="请选择上级主管领导">
                <el-button slot="append" icon="el-icon-search" @click.native="utils.openDialog('2',['realname','username'],['leader1Name','leader1'], that)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="上级分管领导" prop="leader2Name">
              <el-input v-model="form.leader2Name"
                        readonly
                        @click.native="utils.openDialog('2',['realname','username'],['leader2Name','leader2'], that)"
                        placeholder="请选择上级主管领导">
                <el-button slot="append" icon="el-icon-search" @click.native="utils.openDialog('2',['realname','username'],['leader2Name','leader2'], that)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="部门说明" prop="prop1">
              <el-input v-model="form.prop1"/>
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="2">
            <template>
              <el-form-item label="是否管理部门">
                <el-radio v-model="form.ismanagement" label="Y">是</el-radio>
                <el-radio v-model="form.ismanagement" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11">
            <template>
              <el-form-item label="是否生产部门">
                <el-radio v-model="form.ischeckup" label="Y">是</el-radio>
                <el-radio v-model="form.ischeckup" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11" :offset="2">
            <template>
              <el-form-item label="是否停用">
                <el-radio v-model="form.isstop" label="N">正常</el-radio>
                <el-radio v-model="form.isstop" label="Y">停用</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11">
            <template>
              <el-form-item label="维修单位">
                <el-radio v-model="form.prop2" label="Y">是</el-radio>
                <el-radio v-model="form.prop2" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="11" :offset="2">
            <template>
              <el-form-item label="是否统计">
                <el-radio v-model="form.prop3" label="Y">是</el-radio>
                <el-radio v-model="form.prop3" label="N">否</el-radio>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核标准">
              <el-input v-model="form.ipmp" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.memo" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 部门导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :modal="false" :appendToBody="false" width="400px"
               :top="scrollTop" v-dialog-drag :close-on-click-modal="false">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的部门数据
          <el-link     style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">保 存</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <div v-show="exportMenu">
      <ul id="exportMenu" class="exportMenu">
        <li class="exportMenu__item" @click="()=>utils.exportFiles('1',this,'table')"><i class="el-icon-document-remove"></i>导出选中项成XLSX</li>
        <li class="exportMenu__item" @click="()=>utils.exportFiles('2',this,'table')"><i class="el-icon-document"></i>导出本页成XLSX</li>
        <li class="exportMenu__item" @click="()=>utils.exportFiles('3',this,'table')"><i class="el-icon-document-copy"></i>导出所有项成XLSX</li>
      </ul>
    </div>

    <el-dialog title="选择要导出的列" :visible.sync="exportFile" :modal="false" :appendToBody="false" v-dialog-drag
               width="600px" :top="scrollTop" @close="()=>utils.closeExportFile(this)"
    >
      <el-row>
        <el-col :offset="1" :span="5" style="margin-bottom: 10px">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="(val)=>utils.handleCheckAllChange(val,this,codeAll)">全选
          </el-checkbox>
        </el-col>
      </el-row>
      <el-checkbox-group v-model="queryParams.exportColumnName" @change="(val)=>utils.handleCheckedCitiesChange(val,this,codeAll)">
        <el-row>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="name">机构名称</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="branchcode">机构编码</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="managerName">机构主管</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="ismanagement">是否管理部门</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="ischeckup">是否生产部门</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="isstop">是否停用</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="prop2">维修单位</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="prop3">是否统计</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="phone">电话</el-checkbox>
          </el-col>
          <el-col :offset="1" :span="5" style="margin-bottom: 10px">
            <el-checkbox label="fax">传真</el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport">保 存</el-button>
        <el-button @click="exportFile = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--    组织机构-->
    <organization :visibles="organization" :branchcode="form.parentinnercode"
                  @closeDialog="closeOrganization"></organization>
    <!--    角色列表-->
    <userList :visibles.sync="roleList" :branchcode="form.parentinnercode"  @closeDialog="(list)=>utils.closeRole(list,that)"></userList>
  </div>
</template>

<script>
  import {
    getAddList, listDept, getDept, delDept, addDept, updateDept
    , exportDept,
    importTemplate
  } from "@/api/system/dept";
  import {getToken} from "@/utils/auth";
  import service from "../../../utils/request";


  export default {
    name: "Dept",
    components: {},

    data() {
      return {
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        ids: null,
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 表格树数据
        deptList: [],
        // 部门树选项
        deptOptions: [],
        //组织机构弹框
        organization: false,
        roleList: false,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //选项name
        idsName: null,
        // 查询参数
        queryParams: {
          name: undefined,
          exprotDataSize: null,
          exportColumnName: [],
          subCloumn: null,
          exportCheckData: [],
        },
        // 部门导入参数
        upload: {
          // 是否显示弹出层（部门导入）
          open: false,
          // 弹出层标题（部门导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的部门数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: service.baseURL + "/system/dept/importData"
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          parentName: [
            {required: true, message: "上级机构不能为空", trigger: "blur"}
          ],
          name: [
            {required: true, message: "机构名称不能为空", trigger: "blur"}
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          ratednum: [
            {
              pattern: /^-?[1-9]\d*$/g,
              message: "请输入数字格式",
              trigger: "blur"
            }
          ],
          onstaffnum: [
            {
              pattern: /^-?[1-9]\d*$/g,
              message: "请输入数字格式",
              trigger: "blur"
            }
          ],
          offstaffnum: [
            {
              pattern: /^-?[1-9]\d*$/g,
              message: "请输入数字格式",
              trigger: "blur"
            }
          ]
        },
        scrollTop: null,
        exportMenu: false,
        exportFile: false,
        checkAll: false,
        isIndeterminate: false,
        num: null,
        isparentinnercode:true,
        codeAll: ["name", "branchcode", "managerName", "ismanagement", "ischeckup", "isstop", "prop2", "prop3", "phone", "fax"],
        that:this,
        dst:[],
        src:[]
      };
    },
     created() {
      this.getList();
    },
    methods: {
      /** 查询部门列表 */
      getList() {
        this.loading = true;
        listDept(this.queryParams).then(response => {
          this.deptList = this.handleTree(response.data, 'branchinnercode', 'parentinnercode', null, '0');
          this.deptList.sort(this.compare("branchinnercode"))
          this.loading = false;
        });
      },
      //排序方法
      compare(propertyName) {
        return function (object1, object2) {
          var value1 = object1[propertyName];
          var value2 = object2[propertyName];
          if (value2 < value1) {
            return 1;
          } else if (value2 > value1) {
            return -1;
          } else {
            return 0;
          }
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.isparentinnercode=true;
        this.form = {
          branchinnercode: null,
          parentinnercode: null,
          parentName: null,
          name: null,
          branchcode: null,
          fax: null,
          phone: null,
          manager: null,
          managerName: null,
          orderNum: null,
          leader1: null,
          leader2: null,
          leader1Name: null,
          leader2Name: null,
          ratednum: null,
          onstaffnum: null,
          offstaffnum: null,
          ipmp: null,
          prop1: null,
          prop2: null,
          prop3: null,
          memo: null,
          ismanagement: null,
          ischeckup: null,
          isstop: "N"

        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      //打开组织机构弹框
      openOrganization() {
        this.organization = true;
      },
      //关闭组织机构弹框触发的方法
      closeOrganization(list) {
        if (list != undefined && list != [] && list != null) {
          this.form.branchinnercode = list[0].id;
          this.form.branchcodeName = list[0].name;
          this.$refs.form.clearValidate(['branchcodeName'])
        }
        if (this.form.parentinnercode != null || this.form.parentinnercode != ''){
          this.$refs.form.clearValidate(['parentName'])
        }
        this.organization = false;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        var branchinnercode = this.$refs.table.selection[0].branchinnercode;
        getAddList(branchinnercode).then(response => {
          this.open = true;
          this.title = "添加部门";
          this.form.parentinnercode = response.dept.branchinnercode;
          if (this.form.parentinnercode==0){
            this.isparentinnercode=false;
          }
          this.form.parentName = response.dept.name;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        var branchinnercode = row.branchinnercode || this.ids[0];
        getDept(branchinnercode).then(response => {
          console.log(response,'11')
          this.form = response.data;
          this.form.parentName = response.data.parentname;
          this.form.managerName = response.managerName;
          this.form.leader1Name = response.leader1Name;
          this.form.leader2Name = response.leader2Name;
          if (this.form.parentinnercode==0){
            this.isparentinnercode=false;
          }
          this.open = true;
          this.title = "修改部门";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.branchinnercode != undefined) {
              updateDept(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDept(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        var that = this;
        const name = row.name || this.idsName;
        this.$confirm('是否确认删除机构名称为"' + name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delDept(that.ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.branchinnercode);
        this.idsName = selection.map(item => item.name);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "部门导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 导出按钮操作 */
      handleExport() {
        this.utils.handleExport(this,'table',this.deptList,'branchinnercode',exportDept);
      },
    },
    mounted() {
      this.utils.mounteds(this);
    },
    destroyed() {
      this.utils.destroyeds(this);
    }
  };
</script>
<style>
  .dept th .el-checkbox__inner {
    display: none;
  }

  .dept .el-radio__label {
    display: inline-block;
    width: 40px;
  }
</style>
